# -*- coding: utf-8 -*-
"""
BLL层 文件上传.
"""

import time
import sys, shutil, os, string

# 配置：限制的文件范围/类型
ALLOWED_EXTENSIONS=set(['jpg','png','jpeg','JPG'])
# 配置：文件存放路径_临时文件夹
# UPLOAD_FOLDER_FALSE='D:/ImageUp_A/'
# # 配置：文件存放路径_存放文件夹
# UPLOAD_FOLDER_TRUE='D:/ExcelUpPhone_B/'

# SaveUrlByShop='D:/Work/CCC/201704/ImageUp_ByShop/'
# SaveUrlByType='D:/Work/CCC/201704/ImageUp_ByType/'

SaveUrlByShop='D:/HenYanTest/tbh/CCC/201704/ImageUp_ByShop/'
SaveUrlByType='D:/HenYanTest/tbh/CCC/201704/ImageUp_ByType/'

SaveUrlRelativeByShop='ImageUp_ByShop/'
SaveUrlRelativeByType='ImageUp_ByType/'

import DAL.FileUp

# 方法：判断上传文件类型是否在范围之内
def _img_allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 方法：上传图片
# def _api_img_up_01(file):
#     _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}
#
#     if os.path.exists(UPLOAD_FOLDER_FALSE) == False: # 如果文件夹不存在
#         os.makedirs(UPLOAD_FOLDER_FALSE)
#
#
#     if file and _img_allowed_file(file.filename):
#
#         # 重命名
#         now = int(time.time())
#         cs_fileName = 'imgUp_' + str(time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))) + '.png'
#
#         # 保存文件
#         file.save(os.path.join(UPLOAD_FOLDER_FALSE, cs_fileName))
#
#         url_a = UPLOAD_FOLDER_FALSE + cs_fileName
#         # ①判断临时文件是否存在
#         if not os.path.exists(url_a):
#             _respon["ReturnValue"] = 'false'
#             _respon["IsError"] = 'true'
#             _respon["ErrorInfo"]["ErrorMsg"] = 'image up false！'
#         else:
#             _respon["ReturnValue"] = 'true'
#             _respon["IsError"] = 'false'
#             _respon["ErrorInfo"]["ErrorMsg"] = 'image up true！'
#
#
#     else:
#
#         _respon["ReturnValue"] = "false"
#         _respon["IsError"] = "true"
#         _respon["ErrorInfo"]["ErrorMsg"] = "just can up png; [" + file.filename + "] is not png !"
#
#     return _respon

def _api_img_up_byshop(file, cs_GalleryNum,cs_ImgRemark,cs_ImgType,cs_ImgName ,cs_GoodsTypeIDx):#( cs_GalleryNum,url_a,cs_ImgRemark,cs_ImgType ,cs_ImgName,cs_GoodsTypeIDx)
    # GalleryNum  展厅编号
    # ImgRemark    图片备注
    # cs_ImgType   图片类型
    # cs_ImgName     图片名称

    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}

    try:
        if os.path.exists(SaveUrlByShop) == False: # 如果文件夹不存在
            os.makedirs(SaveUrlByShop)
        else:
            pass
    except Exception, e1:
        _respon["ReturnValue"] = "false"
        _respon["IsError"] = "true"
        _respon["ErrorInfo"]["ErrorMsg"] = "creat Error " + str(e1)

        f = open('['+time.strftime("%Y-%m-%d")+'][log].txt', 'a')
        f.write('[' + time.strftime("%Y-%m-%d %H:%M:%S",
                                    time.localtime(
                                        time.time())) + ']' + '[' + str(e1) + ']' + '\n')
        f.close()

    if file and _img_allowed_file(file.filename):

        # 重命名
        now = int(time.time())
        cs_fileName = 'imgUp_' + str(cs_ImgType) + '_' + str(
            time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))) + '.png'

        # 保存文件
        try:
            file.save(os.path.join(SaveUrlByShop, cs_fileName))
        except Exception,e2:
            f = open('[' + time.strftime("%Y-%m-%d") + '][log].txt', 'a')
            f.write('[' + time.strftime("%Y-%m-%d %H:%M:%S",
                                        time.localtime(
                                            time.time())) + ']' + '[' + str(e2) + ']' + '\n')
            f.close()

        url_a = SaveUrlByShop + cs_fileName
        print url_a
        # 判断文件是否存在
        if not os.path.exists(url_a):
            _respon["ReturnValue"] = 'false'
            _respon["IsError"] = 'true'
            _respon["ErrorInfo"]["ErrorMsg"] = 'image up and save false '
        else:
            print "img save ok ",SaveUrlByShop,cs_fileName
            # _respon = DAL.FileUp._api_img_up_byshop( cs_GalleryNum,cs_ImgMang,cs_MainType,cs_ImgName,url_a)
            url_b = SaveUrlRelativeByShop + cs_fileName
            _respon = DAL.FileUp._api_img_up_byshop( cs_GalleryNum,url_b,cs_ImgRemark,cs_ImgType ,cs_ImgName ,cs_GoodsTypeIDx )

    else:

        _respon["ReturnValue"] = "false"
        _respon["IsError"] = "true"
        _respon["ErrorInfo"]["ErrorMsg"] = "just can up png; [" + file.filename + "] is not in 'jpg','png','jpeg','JPG' !"

    return _respon


def _api_img_up_bytype(file,cs_ImgRemark,cs_GoodsTypeID,cs_ImgName):

    # ImgRemark       图片备注
    # GoodsTypeID   图片类型
    # ImgName       图片名称
    # MainImg       图片路径

    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}

    if os.path.exists(SaveUrlByType) == False: # 如果文件夹不存在
        os.makedirs(SaveUrlByType)
    else:
        pass

    if file and _img_allowed_file(file.filename):

        # 重命名
        now = int(time.time())
        # cs_fileName = 'imgUp_' + str(time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))) + '.png'
        cs_fileName = 'imgUp_' + str(cs_GoodsTypeID) + '_' + str(
            time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))) + '.png'

        # 保存文件
        file.save(os.path.join(SaveUrlByType, cs_fileName))

        url_a = SaveUrlByType + cs_fileName
        # 判断文件是否存在
        if not os.path.exists(url_a):
            _respon["ReturnValue"] = 'false'
            _respon["IsError"] = 'true'
            _respon["ErrorInfo"]["ErrorMsg"] = 'image up and save false '
        else:
            url_b = SaveUrlRelativeByType + cs_fileName
            _respon = DAL.FileUp._api_img_up_bytype(cs_ImgRemark, cs_GoodsTypeID, cs_ImgName, url_b)


    else:

        _respon["ReturnValue"] = "false"
        _respon["IsError"] = "true"
        _respon["ErrorInfo"]["ErrorMsg"] = "just can up png; [" + file.filename + "] is not in 'jpg','png','jpeg','JPG' !"

    return _respon